package com.yuanqi.controller;

import com.yuanqi.domain.Supplier;
import com.yuanqi.domain.Customer;
import com.yuanqi.repository.SupplierRepository;
import com.yuanqi.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/finance/reconciliation")
@CrossOrigin(origins = "*")
public class ReconciliationController {
    
    @Autowired
    private SupplierRepository supplierRepository;
    
    @Autowired
    private CustomerRepository customerRepository;
    
    // 注入必要的Repository来查询真实数据
    @Autowired
    private org.springframework.jdbc.core.JdbcTemplate jdbcTemplate;
    
    @GetMapping("/supplier")
    public ResponseEntity<Map<String, Object>> getSupplierReconciliation(
            @RequestParam(required = false) String supplierId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        try {
            // 验证参数
            if (supplierId == null || startDate == null || endDate == null) {
                return ResponseEntity.badRequest().body(Map.of("error", "缺少必要参数"));
            }
            
            // 查找供应商
            Optional<Supplier> supplierOpt = supplierRepository.findById(Long.parseLong(supplierId));
            if (supplierOpt.isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of("error", "供应商不存在"));
            }
            
            Supplier supplier = supplierOpt.get();
            
            // 解析日期
            LocalDate start = LocalDate.parse(startDate);
            LocalDate end = LocalDate.parse(endDate);
            
            // 根据供应商ID和日期范围生成对账单数据（使用真实数据库数据）
            Map<String, Object> reconciliation = generateSupplierReconciliationFromDB(supplier, start, end);
            
            return ResponseEntity.ok(reconciliation);
            
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "生成对账单失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
    
    @GetMapping("/customer")
    public ResponseEntity<Map<String, Object>> getCustomerReconciliation(
            @RequestParam(required = false) String customerId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        try {
            // 验证参数
            if (customerId == null || startDate == null || endDate == null) {
                return ResponseEntity.badRequest().body(Map.of("error", "缺少必要参数"));
            }
            
            // 查找客户
            Optional<Customer> customerOpt = customerRepository.findById(Long.parseLong(customerId));
            if (customerOpt.isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of("error", "客户不存在"));
            }
            
            Customer customer = customerOpt.get();
            
            // 解析日期
            LocalDate start = LocalDate.parse(startDate);
            LocalDate end = LocalDate.parse(endDate);
            
            // 根据客户ID和日期范围生成对账单数据（使用真实数据库数据）
            Map<String, Object> reconciliation = generateCustomerReconciliationFromDB(customer, start, end);
            
            return ResponseEntity.ok(reconciliation);
            
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "生成对账单失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
    
    @PostMapping("/export")
    public ResponseEntity<Map<String, Object>> exportReconciliation(@RequestBody Map<String, Object> exportRequest) {
        // 模拟导出对账单
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "对账单导出成功");
        response.put("downloadUrl", "/api/finance/reconciliation/download/" + System.currentTimeMillis());
        
        return ResponseEntity.ok(response);
    }
    
    private Map<String, Object> createTransactionMap(String date, String type, String reference, 
                                                   Double debit, Double credit, String description) {
        Map<String, Object> transaction = new HashMap<>();
        transaction.put("date", date);
        transaction.put("type", type);
        transaction.put("reference", reference);
        transaction.put("debit", debit);
        transaction.put("credit", credit);
        transaction.put("description", description);
        return transaction;
    }
    
    /**
     * 根据供应商和日期范围从数据库生成对账单数据
     */
    private Map<String, Object> generateSupplierReconciliationFromDB(Supplier supplier, LocalDate startDate, LocalDate endDate) {
        Map<String, Object> reconciliation = new HashMap<>();
        
        // 设置基本信息
        reconciliation.put("supplierName", supplier.getSupplierName());
        reconciliation.put("startDate", startDate.toString());
        reconciliation.put("endDate", endDate.toString());
        
        try {
            // 查询采购订单数据
            String purchaseQuery = """
                SELECT 
                    po.order_code, po.order_date, po.total_amount, po.remark,
                    po.tax_rate, po.tax_amount
                FROM purchase_order po 
                WHERE po.supplier_id = ? 
                AND po.order_date BETWEEN ? AND ?
                ORDER BY po.order_date
                """;
            
            List<Map<String, Object>> purchaseOrders = jdbcTemplate.queryForList(
                purchaseQuery, 
                supplier.getId(), 
                startDate, 
                endDate
            );
            
            // 查询付款记录数据
            String paymentQuery = """
                SELECT 
                    pr.payment_code, pr.payment_date, pr.payment_amount, pr.remark,
                    pr.payment_method, pr.bank_account
                FROM payment_record pr 
                WHERE pr.supplier_id = ? 
                AND pr.payment_date BETWEEN ? AND ?
                ORDER BY pr.payment_date
                """;
            
            List<Map<String, Object>> payments = jdbcTemplate.queryForList(
                paymentQuery, 
                supplier.getId(), 
                startDate, 
                endDate
            );
            
            // 计算总额
            double totalPurchases = purchaseOrders.stream()
                .mapToDouble(order -> ((Number) order.get("total_amount")).doubleValue())
                .sum();
            
            double totalPayments = payments.stream()
                .mapToDouble(payment -> ((Number) payment.get("payment_amount")).doubleValue())
                .sum();
            
            double balance = totalPurchases - totalPayments;
            
            // 构建交易明细
            List<Map<String, Object>> transactions = new ArrayList<>();
            
            // 添加采购订单
            for (Map<String, Object> order : purchaseOrders) {
                transactions.add(createTransactionMap(
                    order.get("order_date").toString(),
                    "采购单",
                    (String) order.get("order_code"),
                    ((Number) order.get("total_amount")).doubleValue(),
                    0.0,
                    (String) order.get("remark")
                ));
            }
            
            // 添加付款记录
            for (Map<String, Object> payment : payments) {
                transactions.add(createTransactionMap(
                    payment.get("payment_date").toString(),
                    "付款",
                    (String) payment.get("payment_code"),
                    0.0,
                    ((Number) payment.get("payment_amount")).doubleValue(),
                    (String) payment.get("remark")
                ));
            }
            
            // 按日期排序
            transactions.sort((a, b) -> a.get("date").toString().compareTo(b.get("date").toString()));
            
            reconciliation.put("totalPurchases", totalPurchases);
            reconciliation.put("totalPayments", totalPayments);
            reconciliation.put("balance", balance);
            reconciliation.put("transactions", transactions);
            
        } catch (Exception e) {
            // 如果查询失败，返回默认数据
            reconciliation.put("totalPurchases", 0.0);
            reconciliation.put("totalPayments", 0.0);
            reconciliation.put("balance", 0.0);
            reconciliation.put("transactions", new ArrayList<>());
            reconciliation.put("error", "查询数据库失败: " + e.getMessage());
        }
        
        return reconciliation;
    }
    
    /**
     * 根据客户和日期范围从数据库生成对账单数据
     */
    private Map<String, Object> generateCustomerReconciliationFromDB(Customer customer, LocalDate startDate, LocalDate endDate) {
        Map<String, Object> reconciliation = new HashMap<>();
        
        // 设置基本信息
        reconciliation.put("customerName", customer.getCustomerName());
        reconciliation.put("startDate", startDate.toString());
        reconciliation.put("endDate", endDate.toString());
        
        try {
            // 查询销售订单数据
            String salesQuery = """
                SELECT 
                    so.order_code, so.order_date, so.total_amount, so.remark,
                    so.tax_rate, so.tax_amount
                FROM sales_order so 
                WHERE so.customer_id = ? 
                AND so.order_date BETWEEN ? AND ?
                ORDER BY so.order_date
                """;
            
            List<Map<String, Object>> salesOrders = jdbcTemplate.queryForList(
                salesQuery, 
                customer.getId(), 
                startDate, 
                endDate
            );
            
            // 查询收款记录数据
            String collectionQuery = """
                SELECT 
                    cr.collection_code, cr.collection_date, cr.collection_amount, cr.remark,
                    cr.collection_method, cr.bank_account
                FROM collection_record cr 
                WHERE cr.customer_id = ? 
                AND cr.collection_date BETWEEN ? AND ?
                ORDER BY cr.collection_date
                """;
            
            List<Map<String, Object>> collections = jdbcTemplate.queryForList(
                collectionQuery, 
                customer.getId(), 
                startDate, 
                endDate
            );
            
            // 计算总额
            double totalSales = salesOrders.stream()
                .mapToDouble(order -> ((Number) order.get("total_amount")).doubleValue())
                .sum();
            
            double totalCollections = collections.stream()
                .mapToDouble(collection -> ((Number) collection.get("collection_amount")).doubleValue())
                .sum();
            
            double balance = totalSales - totalCollections;
            
            // 构建交易明细
            List<Map<String, Object>> transactions = new ArrayList<>();
            
            // 添加销售订单
            for (Map<String, Object> order : salesOrders) {
                transactions.add(createTransactionMap(
                    order.get("order_date").toString(),
                    "销售单",
                    (String) order.get("order_code"),
                    ((Number) order.get("total_amount")).doubleValue(),
                    0.0,
                    (String) order.get("remark")
                ));
            }
            
            // 添加收款记录
            for (Map<String, Object> collection : collections) {
                transactions.add(createTransactionMap(
                    collection.get("collection_date").toString(),
                    "收款",
                    (String) collection.get("collection_code"),
                    0.0,
                    ((Number) collection.get("collection_amount")).doubleValue(),
                    (String) collection.get("remark")
                ));
            }
            
            // 按日期排序
            transactions.sort((a, b) -> a.get("date").toString().compareTo(b.get("date").toString()));
            
            reconciliation.put("totalSales", totalSales);
            reconciliation.put("totalCollections", totalCollections);
            reconciliation.put("balance", balance);
            reconciliation.put("transactions", transactions);
            
        } catch (Exception e) {
            // 如果查询失败，返回默认数据
            reconciliation.put("totalSales", 0.0);
            reconciliation.put("totalCollections", 0.0);
            reconciliation.put("balance", 0.0);
            reconciliation.put("transactions", new ArrayList<>());
            reconciliation.put("error", "查询数据库失败: " + e.getMessage());
        }
        
        return reconciliation;
    }
}


